package com.yiren.backstage.judge.bean;

import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Time:2021/11/12 16:58
 * Author:xiaozan
 * Description:评判树 bean
 */
public class TreeBean implements Serializable {

    /*** 队列集合 */
    private List<NodeBean> treeNodes;

    /*** 队列总数 */
    private int treeNodesSumCount;

    /**
     * 遍历节点至树中
     *
     * @param dirs
     * @return
     */
    public List<NodeBean> buildListToTree(List<NodeBean> dirs) {
        //获取父级ID为0的节点
        List<NodeBean> roots = findRoots(dirs, 0);
        treeNodesSumCount = roots.size();
        //过滤重复值
        List<NodeBean> notRoots = (List<NodeBean>) CollectionUtils.subtract(dirs, roots);
        for (NodeBean root : roots) {
            //设置父级的子级
            root.setChildren(findChildren(root, notRoots));
        }
        return roots;
    }

    /**
     * 返回父级ID为parentID的节点
     *
     * @param allNodes
     * @param parentId
     * @return
     */
    public List<NodeBean> findRoots(List<NodeBean> allNodes, int parentId) {
        List<NodeBean> parentNodes = new ArrayList<>();
        for (NodeBean nodeBean : allNodes) {
            if (null != nodeBean && null != nodeBean.getParentId()) {
                if (nodeBean.getParentId().equals("0")) {
                    parentNodes.add(nodeBean);
                }
            }
        }
        return parentNodes;
    }

    /**
     * 递归查找子级
     *
     * @param root     父级节点
     * @param allNodes 全部节点
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<NodeBean> findChildren(NodeBean root, List<NodeBean> allNodes) {
        List<NodeBean> children = new ArrayList<NodeBean>();

        //root的子级
        for (NodeBean comparedOne : allNodes) {
            if (comparedOne.getParentId().equals(root.getId())) {
                comparedOne.setParent(root);
                children.add(comparedOne);
                treeNodesSumCount++;
            }
        }
        //递归root子级的子级。。。。
        List<NodeBean> notChildren = (List<NodeBean>) CollectionUtils.subtract(allNodes, children);
        for (NodeBean child : children) {
            List<NodeBean> tmpChildren = findChildren(child, notChildren);
            child.setChildren(tmpChildren);
        }
        return children;
    }

    public List<NodeBean> getTreeNodes() {
        return treeNodes;
    }

    public void setTreeNodes(List<NodeBean> treeNodes) {
        this.treeNodes = treeNodes;
    }

    public int getTreeNodesSumCount() {
        return treeNodesSumCount;
    }

    public void setTreeNodesSumCount(int treeNodesSumCount) {
        this.treeNodesSumCount = treeNodesSumCount;
    }
}
